package cn.leftsite.juc.tools;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 公平锁
 *
 * @author wangjinqiang
 * @date 2019-06-03
 */
public class FairLock implements Runnable {
    /**
     * fair 为true , 表示公平锁
     */
    private static final ReentrantLock lock = new ReentrantLock(true);


    @Override
    public void run() {
        while (true) {
            lock.lock();
            try {
                Thread.sleep(500);
                System.out.println(Thread.currentThread().getName() + " 获得锁");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        FairLock r1 = new FairLock();
        Thread t1 = new Thread(r1, "Thread_t1");
        Thread t2 = new Thread(r1, "Thread_t2");
        t1.start();
        t2.start();
    }
}
